﻿/*
* 该文件为CRF表单的运行时js
*/

var isExtranet = window.parent.isExtranet;
var HttpBasePath = window.parent.HttpBasePath;
//病例数据由父页面一次性加载
var formData = window.parent.FormData;
var ProjectID = window.parent.ProjectID;
var PatID = window.parent.PatID;    //Patient表的ID
var RegNo = window.parent.RegNo;
var AdmID = window.parent.AdmID;
var HospitalID = window.parent.HospitalID;
var FormID = window.parent.FormID;

var hasSavedData = false; //判断此表单是否含有已保存的数据

function DataCondition(_tableName,_name,_type,_condition,_value) {
    this.TableName = _tableName;
    this.Name = _name;
    this.Type = _type;
    this.Condition = _condition;
    this.Value = _value;
}

/*
* 解析函数库中的参数的方法
* 由于控件类型不同，控件可能比较复杂，所以，控件的取值需要根据类型来判断，这个跟老版的情况不一样,请修改的同事注意  shebin amend 2016-4-20
* 参数说明： paramStr : 传递到函数库中的参数的原型
* 返回值：参数的数组
*/
function SplitParams(paramStr) {
    var ret = new Array();
    var ParamArr = paramStr.split("SplitP,");
    for (var i = 0; i < ParamArr.length; i++) {
        var TmpParam = ParamArr[i].split("PointP.");
        if (TmpParam.length == 1) {//传入的是值
            ret.push(TmpParam[0].toString());
        } else {  //传入的是表达式
            var sid = '#' + TmpParam[0].toString();
            switch ($(sid).attr("controlType"))
            {
                case "text":
                case "number":
                case "date":
                case "time":
                    {
                        sid = '\'' + '#INPUT' + TmpParam[0].toString() + '\'';
                        break;
                    }
                default:
                    {
                        sid = '\'' + '#' + TmpParam[0].toString() + '\'';
                        break;
                    }
            }
            var expressStr = '$(' + sid + ')' + '.' + TmpParam[1].toString();
            //对字典的情况需要做特殊的处理
            if ($("#" + TmpParam[0]).attr("controltype") == "dictionary" && TmpParam[1].toString() == "val()") {
                expressStr = '$(' + sid + ')' + '.attr("Eval")';
            } else if ($("#" + TmpParam[0]).attr("controltype") == "dictionary" && TmpParam[1].toString() == "text()") {
                expressStr = '$(' + sid + ')' + '.val()';
            }
            var ParamValue = eval("(" + expressStr + ")");
            ret.push(ParamValue);
        }
    }
    return ret;
}

//自定义的Round的方法，四舍五入保留到第N位
//val数值， t保留t位小数
function DHCRound(val, t) {
    return new Number(val.toString().substring(0, val.toString().indexOf(".") + t + 1));
}

//入参如果为带引号的数字转化为纯数字，如果是字符串则原样返回
function FloatStringToFloat(parFloatString) {
    var pattern = new RegExp("^(-?\\d+)(\\.\\d+)?$"); //浮点数正则表达式
    if (pattern.test(parFloatString)) parFloatString = parseFloat(parFloatString);

    return parFloatString;
}

function GetDatas() {
    var ret = new Object();
    if ($("[IsValid=false]").length > 0) {
        ret["Message"] = "表单数据验证未通过";
    } else {
        var DataControls = $("[controlType='text'],[controlType='number'],[controlType='date'],[controlType='time'],[controlType='email'],[controlType='dictionary']");
        for (var i = 0; i < DataControls.length; i++) {
            var cur$Obj = $(DataControls[i]);
            var conInfo = eval("(" + $(DataControls[i]).attr("ConfigInfo") + ")");
            if (conInfo.Code != null && conInfo.Code != "") {
                var curType = cur$Obj.attr("controlType");
                if (curType == "dictionary") {
                    ret[conInfo.DataFieldName] = escape(cur$Obj.find("select").multipleSelect('getSelects', "text"));

                    var vals = escape(cur$Obj.find("select").multipleSelect('getSelects', "value"));
                } else {
                    ret[conInfo.DataFieldName] = escape($(DataControls[i]).find("input,textarea").val());
                }
            }
        }
    }
    
    return $.toJSON(ret);
}

//查找属性等于指定值的对象，returnArr：是否返回数组
function FindObjByPropValue(objArr, prop, value, returnArr) {
    if (!objArr || objArr.length == 0 || !prop) return null;

    var flag = false;
    var ret = new Array();

    for (var i = 0; i < objArr.length; i++) {
        if (objArr[i][prop] && objArr[i][prop] == value) {
            if (returnArr) {
                ret.push(objArr[i]);
            } else {
                return objArr[i];
            }

            flag = true;
        }
    }

    return flag ? ret : null;
}

function getLeft($obj) {
    var ret = 0;
    if ($obj && $obj.length > 0) {
        var controlType = $obj.attr("controlType");

        switch (controlType) {
            case "dictionary":
                {
                    ret = $obj.position().left + $obj.width() + 1;
                    break;
                }
            case "date":
                {
                    ret = $obj.position().left + $obj.width() - 9;
                    break;
                }
            default:
                {
                    ret = $obj.position().left + $obj.width() + 1;
                    break;
                }
        }
    }

    return ret;
}

function getTop($obj) {
    var ret = 0;
    if ($obj && $obj.length > 0) {
        var controlType = $obj.attr("controlType");

        if ($obj.parent().prop("tagName") == "TD") {
            ret = $obj.position().top + $obj.height() - 20;

        } else {
            switch (controlType) {
                case "dictionary":
                    {
                        ret = $obj.position().top + $obj.find("button").height() - 20;
                        break;
                    }
                default:
                    {
                        ret = $obj.position().top + $obj.find("input,textarea").height() - 8;
                        break;
                    }
            }
        }
    }

    return ret;
}

function GetThWidth(elWidth,propCount) {
    var ret=0;

    if (elWidth / propCount > 50) {
        ret = elWidth / propCount;
    } else {
        ret = 50;
    }

    return ret;
}

//获取外部接口数据,异步
function LoadExternalData() {

    //这里暂时写死，当不是协和医院时，不获取外部数据
    if (!FormID || !AdmID || AdmID == "" || HospitalID != 30) return;

    $.ajax({
        type: "POST",
        url: HttpBasePath + "/CaseBrowse/GetExternalDataByAdmID",
        dataType: "json",
        data: { FormID: FormID, AdmID: AdmID },
        async: true,
        success: function (ret) {
            if (ret.Result) {
                if (ret.DataObject) {

                    var ItemPropInfo = eval("(" + ret.Message + ")");

                    ExDataCallBack(ret.DataObject, ItemPropInfo);
                }
            } else {

                alert("获取外部接口数据失败！错误信息：" + ret.Message);
            }
        }
    });

}

function ExDataCallBack(ExternalDataArr, ItemPropInfo) {
    if (!ExternalDataArr || ExternalDataArr.length == 0) return;

    var fieldControls = $("*[configinfo]");
    fieldControls.each(function (index, d) {

        var thisEl = $(d);

        var configStr = $(d).attr("configinfo");
        if (configStr) {
            curConfigObj = eval("(" + configStr + ")");
            //过滤字段控件
            if (curConfigObj && curConfigObj.DataFieldName) {

                var curDataObj = FindObjByPropValue(ExternalDataArr, "DataFieldName", curConfigObj.DataFieldName, false);

                if (curDataObj) {

                    //外部数据信息
                    var exData = null;
                    if (curDataObj.Data) exData = curDataObj.Data;
                    var fieldName = curDataObj.DataFieldName;
                    var itemPropOutCode = curDataObj.ItemPropOutCode;
                    var itemParentCateID = curDataObj.ItemParentCateID;

                    //外部数据返回可能是对象或者数组
                    if (exData && exData.length > 0 && exData[0] && exData[0].length > 0) exData = exData[0];

                    //事件绑定
                    thisEl.mouseover(function () {
                        //移除之前的按钮
                        $("#exBtn").remove();

                        //生成点击按钮
                        var btnLeft = getLeft(thisEl);
                        var btnTop = getTop(thisEl);
                        var btnHtml = '<input id="exBtn" type="button" style="width: 25px; height: 20px; position: absolute; left: ' + btnLeft + 'px; top: ' + btnTop + 'px; z-index:100; font-size:13px; font-weight:bold; line-height:10px;" value="…"/>';
                        $(this).after(btnHtml);

                        //获取所在分类的各个属性,拼接表头
                        var curPropInfo = FindObjByPropValue(ItemPropInfo, "ItemCateID", itemParentCateID, true);
                        var thHtml = '<tr>';
                        $(curPropInfo).each(function (i, d) {
                            thHtml += '<th style="background:#428BCA; border:1px solid #428BCA; border-right:1px solid #DDDDDD; width:' + GetThWidth(thisEl.width(), curPropInfo.length) + 'px;">' + d.Name + '</th>';
                        });
                        thHtml += '<th style="width:50px; background:#428BCA; border:1px solid #428BCA; border-left:0;"></th></tr>';

                        //拼接数据
                        var tdHtml = "";
                        if (exData && exData.length > 0) {

                            //确保有数据,有相应属性
                            if (exData[0][itemPropOutCode]) {
                                for (var i = 0; i < exData.length; i++) {
                                    tdHtml += '<tr style="background:#EEEEEE;">';
                                    $(curPropInfo).each(function (index, d) {
                                        tdHtml += '<td style="padding-top:5px; padding-bottom:6px; font-weight: normal; font-size: 16px; color: rgb(102, 102, 102);" name="' + d.OutCode + '">' + exData[i][d.OutCode] + '</td>';
                                    });
                                    tdHtml += '<td><input type="button" style="font-size:10px;" value="选择"/></td></tr>';
                                }
                            }
                        }

                        var dataLeft = thisEl.position().left - 1;
                        var dataTop = thisEl.position().top + thisEl.height() - 7;
                        var dataHtml = '<div id="exData" style="position: absolute; border-top-color: rgb(250, 247, 247); border-left-color: rgb(250, 247, 247); border-width: 1px 0px 0px 1px; border-style: solid dashed dashed solid; display:none; left: ' + dataLeft + 'px; top: ' + dataTop + 'px; z-index:100;">'
                                    + '<table class="table table-bordered"><tbody>'
                                    + thHtml + tdHtml
                                    + '</tbody></table></div>';

                        if ($("#exData").length > 0) {
                            $("#exData").remove();
                        }
                        $("#exBtn").after(dataHtml);

                        //点击选择值
                        $("#exData input[type='button']").click(function () {
                            var curValue = $(this).parent().parent().find("td[name='" + itemPropOutCode + "']").html();

                            setValue(thisEl, curValue);

                            $("#exData").hide();

                        });

                        //按钮事件
                        $("#exBtn").click(function () {
                            if ($("#exData").is(":hidden")) {
                                $("#exData").show();

                            } else {
                                $("#exData").hide();
                            }
                        });
                    });

                    //当此表单未填数据时，默认填写外部数据的最后一项数据
                    if (!hasSavedData) {
                        if (exData && exData.length > 0) {
                            setValue(thisEl, exData[exData.length - 1][itemPropOutCode]);
                        }
                    }
                }
            }
        }
    });
}

function testPosition() {
    $("*[configinfo]").each(function (i, d) {
        var configStr = $(d).attr("configinfo");
        if (configStr) {
            curConfigObj = eval("(" + configStr + ")");
            //过滤字段控件
            if (curConfigObj && curConfigObj.DataFieldName) {

                {
                    //生成点击按钮
                    var btnLeft = getLeft($(d));
                    var btnTop = getTop($(d));
                    var btnHtml = '<input type="button" style="width: 25px; height: 20px; position: absolute; left: ' + btnLeft + 'px; top: ' + btnTop + 'px; z-index:100; font-size:14px; font-weight:bold; line-height:10px;" value="..."/>';
                    $(d).after(btnHtml);
                }
            }
        }
    });
}

function InitData() {
    if (!formData) return;
    var DataControls = $("[controlType='text'],[controlType='number'],[controlType='date'],[controlType='time'],[controlType='email'],[controlType='dictionary']");
    for (var i = 0; i < DataControls.length; i++) {
        var cur$Obj = $(DataControls[i]);
        var conInfo = eval("(" + $(DataControls[i]).attr("ConfigInfo") + ")");
        if (conInfo.DataFieldName) {

            if (formData[conInfo.DataFieldName]) {
                hasSavedData = true;
                setValue($(DataControls[i]), formData[conInfo.DataFieldName]);
            }
        }
    }

}

function SaveData(isExtranet) {
    var result = null;
    var flag = true;
    
    $("[isRequired=1]").each(function () {

        var curType = $(this).attr("controlType");
        var curValue = null;
        if (curType == "dictionary") {
            curValue = $(this).find("select").multipleSelect('getSelects', "text");

            //移除样式
            $(this).find("button:first").removeClass("requiredField requiredOK");
        } else {
            curValue = $(this).find("input,textarea").val();

            //移除样式
            $(this).find("input,textarea").removeClass("requiredField requiredOK");
        }
        if (isExtranet) {
            if (!curValue || curValue.length == 0) {

                //未填写做出提示
                if (curType == "dictionary") {
                    $(this).find("button:first").addClass("requiredField");
                } else {
                    $(this).find("input,textarea").addClass("requiredField");
                }

                flag = false;

            } else {
                // 
                if (curType == "dictionary") {
                    $(this).find("button:first").addClass("requiredOK");
                } else {
                    $(this).find("input,textarea").addClass("requiredOK");
                }
            }
        }
        
    });

    if (!flag) {
        result = "表单有必填项未填写！";
    } else {
        var fieldArr = new Array();
        //保存到PatFormData表
        var formDataObj = new Object();
        var DataControls = $("[controlType='text'],[controlType='number'],[controlType='date'],[controlType='time'],[controlType='email'],[controlType='dictionary']");
        for (var i = 0; i < DataControls.length; i++) {
            var cur$Obj = $(DataControls[i]);
            var conInfo = eval("(" + cur$Obj.attr("ConfigInfo") + ")");
            if (conInfo.DataFieldName) {
                //获取各字段值
                //alert(cur$Obj.find("input").val());
                var curType = cur$Obj.attr("controlType");
                if (curType == "dictionary") {
                    var curField = new DataCondition("", conInfo.DataFieldName, cur$Obj.attr("controlType"), "", [escape(cur$Obj.find("select").multipleSelect('getSelects', "text"))]);
                    formDataObj[conInfo.DataFieldName] = escape(cur$Obj.find("select").multipleSelect('getSelects', "text"));
                } else {
                    var curField = new DataCondition("", conInfo.DataFieldName, cur$Obj.attr("controlType"), "", [escape(cur$Obj.find("input,textarea").val())]);
                    formDataObj[conInfo.DataFieldName] = escape(cur$Obj.find("input,textarea").val());
                }
              
                fieldArr.push(curField);
            }
        }

        $.ajax({
            type: "POST",
            url: HttpBasePath + "/CaseBrowse/AddOrUpdateFormData",
            dataType: "json",
            async: false,
            data: { ProjectID: ProjectID, PatID: PatID, FieldData: $.toJSON(fieldArr), FormID: FormID, FormData: $.toJSON(formDataObj) },
            success: function (ret) {
                if (ret.Result) {
                    result = true;
                    //alert("表单信息保存完毕！");
                } else {
                    result = "表单信息保存失败！错误信息：" + ret.Message;
                }
            },
            error: function (e, i) {

            }
        });
    }

    return result;
}

function setValue($obj, parValue) {
    if (!parValue) return;

    var curControlType = $obj.attr("controlType");
    switch (curControlType) {
        case "dictionary":
            {
                if (parValue != undefined) {
                    //注意：这里字典命名是不能出现英文字符的‘,’符合,否则这里会截取字符串错误
                    var curValues = parValue.split(",");
                    $obj.find("select").multipleSelect('setSelects', curValues);
                }
                break;
            }
        default:
            {
                $obj.find("input,textarea").val(parValue);
                break;
            }
    }
}


$(function () {
    //通过前台得到BasePath
    var GetBasePath = function () {
        var iPos = location.href.indexOf("://");
        var urlArr = location.href.substring(iPos + 3).split("/");
        var localstr = location.href.substring(0, iPos + 2);
        for (var i = 0; i < urlArr.length; i++) {
            if (urlArr[i] == "WebDesigner") {
                return localstr;
            } else {
                localstr += "/" + urlArr[i];
            }
        }
        return localstr;
    }
    //定义这个变量
    var basePath = GetBasePath();
    //对dictionary的处理
    var dicControls = $("[controlType='dictionary']");
    dicControls.each(function () {
        var curEl = $(this);
        var elem = $(this).find("select");
        var ret = elem.parent().attr("ConfigInfo");
        var conInfo = eval("(" + ret + ")");

        var isSingle = conInfo.SingleSelect == 1 ? true : false;   //是否是单选
        var isFilter = false;   //是否显示查询框
        var optionNum = 0;  //记录字典选项的个数
        curEl.find(".ms-parent").remove();  //移除默认的.ms-parent
        //判断是自动生成的还是新建的字典控件
        if (conInfo.DicTableID == null || conInfo.DicTableID == "") {
            optionNum = 0;
            isFilter = false;
            elem.multipleSelect({
                placeholder: "请选择",
                single: isSingle, //单选
                filter: isFilter  //查询 
            });
        } else {
            $.ajax({
                type: "POST",
                url: basePath + "/DictionaryManage/GetTree",
                data: { parDicTableID: conInfo.DicTableID },
                success: function (msg) {
                    var optionStr = "";
                    if (msg.Result) {
                        elem.find("option").remove();  //移除默认的选项
                        zNodes = msg.DataObject;
                        optionNum = zNodes.length;

                        for (var n = 0; n < zNodes.length; n++) {
                            var value = zNodes[n].id;
                            var text = zNodes[n].name;
                            isFilter = optionNum <= 5 ? false : true;  //设置超过五个选项时显示查询框
                            var $opt = "";
                            if (zNodes[n].children.length > 0) {
                                //做多级处理。暂时只能支持两级，三级及三级以上需完善
                                $opt += '<optgroup label="' + text + '">'
                                for (var c = 0 ; c < zNodes.children.length; c++) {
                                    var childValue = zNodes[n].children[c].id;
                                    var childText = zNodes[n].children[c].name;

                                    $opt += '<option value="' + childValue + '">' + childText + '</option>';
                                }
                                $opt += '</optgroup>';
                            } else {
                                $opt = $("<option />", {
                                    value: text,  //这里值和text暂时都用文本了，
                                    text: text
                                });
                            }
                            elem.multipleSelect({
                                placeholder: "请选择",
                                single: isSingle, //单选
                                filter: isFilter,  //查询 
                                onOpen: function () {

                                },
                                onClose: function () {
                                    //alert(elem.multipleSelect('getSelects', "text"));
                                }
                            });
                            //通过 AJAX 或者 DOM 来手动添加或者删除 option 选项，可以通过 refresh 方法来重新加载
                            elem.append($opt).multipleSelect("refresh");
                            
                        }
                    }
                },
                error: function (r, s, e) {
                    alert("出错：" + e);
                },
                async: false
            });
        }
    });


    //对日期控件的处理
    var dicControls = $("[controlType='date']");
    dicControls.find("input").removeAttr("type");
    dicControls.find("input").datepicker({
        onClose: function (dateText, inst) {
            $(this).blur();
        }
    });
    dicControls.find("input").datepicker("option", "dateFormat", "yy-mm-dd");
    dicControls.find("button").click(function () {
        $(this).parent().find("input").datepicker('show');
    });

    var ErrorMessageMapping = new Object();
    ErrorMessageMapping["ValidEmail"] = "电子邮箱格式错误";
    ErrorMessageMapping["ValidDate"] = "日期格式错误";
    ErrorMessageMapping["ValidDateTime"] = "日期时间格式错误";
    //处理表单的前台验证
    $("[controlType='text'],[controlType='number'],[controlType='date'],[controlType='time'],[controlType='email']").find("input,textarea").blur(function () {
        var conInfo = eval("(" + $(this).parent().attr("ConfigInfo") + ")");
        if (conInfo.Expression != null && conInfo.Expression != "") {
            $(".label").remove();
            if ($(this).val() != "") {
                var exps = conInfo.Expression.split(",");
                for (var i = 0; i < exps.length; i++) {
                    var ret = eval(exps[i] + "('" + $(this).val() + "')");
                    if (!ret) {
                        $(this).parent().attr("IsValid", false);
                        var msg = conInfo.CName + "验证失败:" + ErrorMessageMapping[exps[i]];
                        var msgLeft = parseInt($(this).parent().css("left").replace("px", "")) + parseInt($(this).parent().css("width").replace("px", "")) + 20 + "px";
                        var msgHtm = "<span class='label label-danger' style='position:absolute; left:" + msgLeft + "; top:" + $(this).parent().css("top") + "; height:33px; line-height:25px; font-size:14px;'><i class='fa fa-remove'></i> " + msg + "</span>";
                        $(this).parent().parent().append(msgHtm);
                    } else {
                        $(this).parent().removeAttr("IsValid");
                        var msg = conInfo.CName + "验证成功。";
                        var msgLeft = parseInt($(this).parent().css("left").replace("px", "")) + parseInt($(this).parent().css("width").replace("px", "")) + 20 + "px";
                        var msgHtm = "<span class='label label-success' style='position:absolute; left:" + msgLeft + "; top:" + $(this).parent().css("top") + "; height:33px; line-height:25px; font-size:14px;'><i class='fa fa-check'></i> " + msg + "</span>";
                        $(this).parent().parent().append(msgHtm);
                    }
                }
            }
        }
    });

    //绑定配置的事件  shebin amend 2016-4-20
    $("[controlType]").each(function (i, d) {
        //var configInfo = eval("(" + $(d).attr("ConfigInfo") + ")");
        var configInfo = eval("(" + $(d).attr("EventConfig") + ")");  //获取事件配置属性 EventConfig
        //EventConfig属性是否存在判断 add by chengl
        if (configInfo)
        {
            //控件单击事件的处理，其他事件与之类似
            if (configInfo.EventClick != null && configInfo.EventClick != "") {
                var eventObj = eval("(" + configInfo.EventClick + ")");
                switch ($(d).attr("controlType"))
                {
                    case "text":
                    case "number":
                    case "date":
                        {
                            $(d).find("input").click(function () {
                                eval(eval(eventObj.expStr));
                            });
                            break;
                        }
                }
            }
            //控件左键双击事件的处理
            if (configInfo.EventDBLClick != null && configInfo.EventDBLClick != "") {
                var eventObj = eval("(" + configInfo.EventDBLClick + ")");
                switch ($(d).attr("controlType")) {
                    case "text":
                    case "number":
                    case "date":
                        {
                            $(d).find("input").dblclick(function () {
                                eval(eval(eventObj.expStr));
                            });
                            break;
                        }
                }
            }
            //控件获得焦点事件的处理
            if (configInfo.EventEnter != null && configInfo.EventEnter != "") {
                var eventObj = eval("(" + configInfo.EventEnter + ")");
                switch ($(d).attr("controlType")) {
                    case "text":
                    case "number":
                    case "date":
                        {
                            $(d).find("input").focus(function () {
                                eval(eval(eventObj.expStr));
                            });
                            break;
                        }
                }
            }
            //控件失去焦点事件的处理,这个比较特殊，需要兼容默认的验证事件（jQuery应该可以绑定多个事件，不影响验证，还未测，shebin 2016-4-19）
            if (configInfo.EventBlur != null && configInfo.EventBlur != "") {
                var eventObj = eval("(" + configInfo.EventBlur + ")");
                switch ($(d).attr("controlType")) {
                    case "text":
                    case "number":
                    case "date":
                        {
                            $(d).find("input").blur(function () {
                                eval(eval(eventObj.expStr));
                            });
                            break;
                        }
                }
            }
        }
    });
});

$(document).ready(function () {

    //加载表单数据
    InitData();

    //加载外部数据
    if (!isExtranet) {
        LoadExternalData();
    }

    //testPosition();

    $("label").each(function () {

        var curHtml = $(this).html();
        var curHtmlArr = curHtml.split("*");

        if (curHtmlArr.length == 2) {
            $(this).html("<b style='color:red'>*</b>" + curHtmlArr[1]);
        }
    });

    $("label").css({ "font-weight": "normal", "font-size": "13px", "color": "rgb(8A, 8A, 8A)" });
    //设置字典下拉框选项的风格
    $(".ms-parent").find(".ms-drop").find("label").css({ "font-weight": "normal", "font-size": "13px", "color": "rgb(8A, 8A, 8A)" })
});